<template>
	<view class="container fc plr_28">
		<view class="mt_32">
			<image class="ib width_80 height_80 br50" :src="dealInfo.logo" mode="aspectFit"></image>
		</view>
		<view class="mt_32" v-if="type === 1">
			<!--  <button open-type="getUserInfo" @getuserinfo="getuserinfo" class="w_100 custom_btn lh_44 primary br_57 fz_14">
        微信一键登录(基本信息)
      </button> -->
			<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
				class="w_100 custom_btn lh_44 primary br_57 fz_14">
				手机号快捷登录
			</button>
		</view>
		<view class="mt_56" v-else-if="type === 2">
			<view class="fz_16">
				<view class="fx fl pb_12 bob_1 boc_grey">
					<input v-model="account" maxlength="11" placeholder="请输入手机号" class="fx_1" type="number" />
				</view>
				<view class="fx fl pb_12 bob_1 boc_grey mt_16">
					<input placeholder="请输入密码" class="fx_1" :password="isPsd" v-model="password" />
					<view class="password_icon" @click="bindVisiblePassword">
						<u-icon class="" :name="isPsd ? 'eye-fill' : 'eye-off'" size="48rpx" color="#E7E7E7"></u-icon>
						<!-- <u-icon class="" :name="isPsd ? 'eye-fill' : 'eye-off'" size="48rpx" color="#E7E7E7"></u-icon> -->
					</view>

				</view>
			</view>
		</view>
		<view class="mt_56" v-else>
			<view class="fz_16">
				<view class="fx fl pb_12 bob_1 boc_grey">
					<input v-model="account" maxlength="11" placeholder="请输入手机号" class="fx_1" type="number" />
				</view>
				<view class="fx fl pb_12 bob_1 boc_grey mt_16">
					<input v-model="captcha" maxlength="6" placeholder="请输入验证码" class="fx_1" type="number" />
					<text class="fc_primary" @tap="handleGetCode">{{ verifyTips }}</text>
				</view>
				<view class="fx fl pb_12 bob_1 boc_grey mt_16" v-if="!isRegist">
					<view class="fx fl">
						<view class="fb width_98 fx_sh"> 邀请人ID </view>
						<input v-model="shareId" placeholder="请输入邀请人ID" class="fx_1" type="number"
							:disabled="!!customerId" />
					</view>
				</view>
			</view>
		</view>
		<view class="fr mt_12" v-if="type == 2">
			<view class="fz_12" hover-class="none" @click="bindForgetPassword">
				忘记密码？
			</view>
			<!-- <navigator class="fz_12" url="/pages/person/pages/login_password" hover-class="none">忘记密码？</navigator> -->
		</view>
		<view class="mt_32" v-if="type !== 1">
			<button
				:disabled="isRegist ? !((captcha || password) && account) : !(captcha || password) && account && shareId"
				class="w_100 custom_btn lh_44 primary br_57 fz_14" @click="handleLogin">
				{{ isRegist ? "登录" : "注册" }}
			</button>
		</view>
		<view class="fx jcb mt_24 fb">
			<text @click="type = 2" v-if="type != 2">账号密码登录</text>
			<text @click="type = 3" v-if="type != 3">手机号验证登录</text>
			<text @click="type = 1" v-if="type != 1">手机号快捷登录</text>
			<!-- <text @click="type = 1" v-if="type != 1">微信一键登录</text> -->
		</view>
		
		<u-checkbox-group v-model="agree" shape="circle">
			<label class="pf l_0 b_0 r_0 pbsafe_37 fx jcc aic fz_12 fc_999">
				<u-checkbox activeColor="#F08519" name="1"></u-checkbox>
				<text>已阅读并同意<text class="fc_primary"
						@click.stop="handleProtocol('consumer_agreement')">《用户协议》</text>和<text class="fc_primary"
						@click.stop="handleProtocol('private_agreement')">《隐私政策》</text></text>
			</label>
		</u-checkbox-group>
		<u-toast ref="uToast"></u-toast>
		<u-code :seconds="seconds" ref="uCode" @change="codeChange" unique-key="login" :keepRunning="true"></u-code>
	</view>
</template>

<script>
	import api from "@/service/config/api";
	import verifyCode from "@/mixins/verify_code.js";
	import {
		showToast
	} from "../../../utils";
	import {
		mapState
	} from 'vuex'
	export default {
		mixins: [verifyCode],
		data() {
			return {
				type: 3, // 登录类型 1-一键登录 2-密码登录 3-验证码登录
				captcha: "", // 验证码/密码
				account: "", // 手机号
				password: "",
				isPsd: true,
				isRegist: true, // 手机号是否已经注册
				isRequest: false, // 是否请求过账户是否存在接口
				preString: "",
				backUrl: "/pages/index/index",
				userInfo: {},
				wechatNumber: "",
				wechatIsRegist: false,
				shareId: "",
				agree: false,
				customerId: '',
				isRequestWechat: false
			};
		},
		onLoad(options) {
			console.log('页面加载')
			console.log("appId")
			console.log(this.appId)
			console.log(options)
			// console.log(uni.getUserProfile({

			// }))
			if (options.customerId) {
				this.customerId = options.customerId
				this.shareId = options.customerId
			}
			console.log("this.$storage.getItem('shareId')", this.$storage.getItem('shareId'))
			if (this.$storage.getItem('shareId')) {
				this.customerId = this.$storage.getItem('shareId')
				this.shareId = this.$storage.getItem('shareId')
			}
			this.backUrl = options.backUrl ? options.backUrl : "/pages/index/index";
		},
		computed: {
			...mapState(['appId','dealInfo']),
		},
		watch: {
			account(newValue, oldValue) {
				if (newValue != oldValue) {
					this.isRequest = false;
					// this.shareId = ""
					this.isRegist = true
					if (!this.isRequestWechat) {
						this.captcha = ""
					}
				}
				console.log("手机号码发生变化");
			},
			type(newValue, oldValue) {
				if (newValue != oldValue) {
					this.account = ""
					this.captcha = ""
					this.password = ""
					this.isRequestWechat = false
				}
			}
		},
		// onShow() {
		// 	uni.onBackPress(this.handleBack);
		// 	// const pages = getCurrentPages();
		// 	// const currentPage = pages[pages.length - 1];
		// 	// console.log("再次进入")
		// 	// console.log(pages)
		// 	// console.log(currentPage)
		// 	// if (currentPage.$vm && currentPage.$vm.isFromBack) {
		// 	// 	console.log("通过返回按钮进入");
		// 	// 	this.captcha = ""
		// 	// 	this.account = ""
		// 	// 	this.password = ""
		// 	// 	this.isRegist = true
		// 	// 	this.isRequest = false
		// 	// }
		// },
		onShow() {
			// 监听清空输入框的事件
			// uni.$on('clearInput', () => {
			// 	this.captcha = ""
			// 	this.account = ""
			// 	this.password = ""
			// 	this.isRegist = true
			// 	this.isRequest = false
			// });
		},
		onHide() {
			// 页面隐藏时移除监听，避免重复执行
			// uni.$off('clearInput');
		},
		methods: {
			handleProtocol(type) {
				uni.navigateTo({
					url: '/pages/common/pages/richtext?key=' + type
				})
			},
			reloadPage() {
				console.log("通过返回按钮进入")
				this.captcha = ""
				this.account = ""
				this.password = ""
				this.isRegist = true
				this.isRequest = false
			},
			bindVisiblePassword() {
				this.isPsd = !this.isPsd
			},
			// 忘记密码
			bindForgetPassword() {
				// if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(this.account))
				// 	return this.$utils.showToast("请输入正确的手机号码");
				console.log("这里3")
				uni.navigateTo({
					url: `/pages/person/pages/forget_pass?phone=${this.account}`
				})
			},
			// 获取微信用户手机号码
			getPhoneNumber(info) {
				// uni.showToast({
				//  title:"获取手机号码"
				// })
				if (!this.agree) return this.$utils.showToast("您需要阅读并接受用户协议及隐私政策！");
				console.log("手机好嘛信息")
				console.log(info)
				let numberInfo = info.detail

				if (numberInfo.errMsg == "getPhoneNumber:ok") {
					this.getPhoneNumberByCode(numberInfo.code)
				} else {
					this.$utils.showToast("获取微信信息失败");
				}
				console.log("手机号码")
				console.log(numberInfo.code)
			},
			registCallBack() {},
			// 获取用户手机号码
			getPhoneNumberByCode(phoneCode) {
				api.post(`/user/api/auth/getWechatPhone/${phoneCode}`, {}, {
					noCheck: true
				}).then(res => {
					console.log("微信登录")
					console.log(res)
					if (res && res.code == 0) {
						this.account = res.data.phone
						this.captcha = res.data.code
						this.isRequestWechat = true
						console.log(this.account)
						console.log(this.captcha)
						this.numberIsRegist("wechat", res.data.phone, null)
					}

				})
			},
			// 获取微信用户信息
			getuserinfo(info) {
				this.userinfo = info.detail.userInfo
				uni.showToast({
					title: this.userInfo
				})
			},
			handleGetCode() {
				if (!this.account) return this.$utils.showToast("请填写手机号码");
				if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(this.account))
					return this.$utils.showToast("请输入正确的手机号码");
				// this.getCode();
				if (!this.isRegist && this.isRequest) {
					this.getCode()
				} else {
					this.numberIsRegist("code", this.account, null)
				}
			},
			getVerify() {
				api.get("/user/api/auth/sendLoginSms/" + this.account, {}, {
					noCheck: true
				}).then((res) => {
					this.showSend();
				});
			},
			// 页面跳转
			bindPage() {
				this.$storage.removeItem('shareId')
				uni.reLaunch({
					url: decodeURIComponent(this.backUrl)
				})
			},
			// 登录
			handleLogin() {
				if (!this.account) return this.$utils.showToast("请填写手机号码");
				if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(this.account))
					return this.$utils.showToast("请输入正确的手机号码");
				if (this.type == 3) {

					if (!this.captcha)
						return this.$utils.showToast(
							"请填写验证码"
						);
				}
				if (this.type == 2) {
					if (!this.password)
						return this.$utils.showToast(
							"请填写密码"
						);
				}
				if (!/^[\w\d]+$/i.test(this.captcha) && this.type == 1)
					return this.$utils.showToast("请输入正确的验证码");
				if (!this.agree) {
					return this.$utils.showToast("您需要阅读并接受用户协议及隐私政策！");
				}
				if (this.type == 1) {
					console.log("一键登陆")
				} else if (this.type == 2) {
					console.log("密码登陆111")
					if (this.isRequest) {
						if (this.isRegist) {
							this.loginByPassword()
							// this.userLogin();
						} else {
							this.$utils.showToast("该帐号未注册，请切换验证码登陆注册！");
							// this.userRegist();
						}
					} else {
						this.numberIsRegist("password", this.account, null)

					}
				} else {
					console.log("验证码登陆")
					if (this.isRequest) {
						if (this.isRegist) {
							this.userLogin();
						} else {
							if (!this.shareId) {
								return this.$utils.showToast("请输入邀请人ID");
							}
							this.userRegist();
						}
					} else {
						this.numberIsRegist("phone", this.account, null)

					}
				}
			},
			// 密码登陆
			loginByPassword() {
				const that = this
				api.post(
					`/auth/oauth2/token?username=${this.account}&grant_type=password&scope=server&password=${this.password}`, {
						password:this.password
					}, {
						isLogin: true,
						noCheck: true,
						
					}).then(res => {
					if (res && res.user_id) {
						this.$storage.setItem("token", res.access_token);
						this.$store.commit('setToken', res.access_token)
						this.$storage.setItem("tokenType", res.token_type);
						this.$storage.setItem("refreshToken", res.refresh_token);
						that.getBasicUserInfo()
					}

					if (res && res.code == 1) {
						if (res.msg == "未设置登录密码,请先设置登录密码！") {
							uni.$u.toast("密码有误，可通过忘记密码重置");
							// setTimeout(() => {
							// 	uni.navigateTo({
							// 	url: "/pages/person/pages/login_password"
							// })
							// }, 1500);

						}
						if (res.msg == "用户名不存在或者密码错误") {
							uni.$u.toast("密码有误，可通过忘记密码重置");
						}

					}
				})
			},
			// 手机号码是否注册
			numberIsRegist(type, phoneNumber, callback) {
				api.get("/user/api/auth/exit/" + this.account, {}, {
					noCheck: true
				}).then((res) => {
					console.log(res);
					if (type == "code") {

						if (!res.data) {
							this.isRegist = false;
							this.isRequest = true;
							uni.$u.toast("手机号未注册");
							// userRegist();
						} else {
							// this.getCode();
						}
						this.getCode();
					}
					if (type == "phone") {
						if (!res.data) {
							this.isRegist = false;
							this.isRequest = true;
							uni.$u.toast("手机号未注册");
							// userRegist();
						} else {
							this.userLogin(type);
						}
					}
					if (type == "password") {
						if (!res.data) {
							this.isRegist = false;
							this.isRequest = true;
							uni.$u.toast("该帐号未注册，请切换验证码登陆注册！");
							// userRegist();
						} else {
							this.loginByPassword()
							// this.userLogin(type);
						}
					}
					if (type == "wechat") {
						if (res.data) {
							this.userLogin(type)
						} else {
							console.log("这里4")
							uni.navigateTo({
								url: `/pages/account/pages/info?phone=${this.account}&code=${this.captcha}&backUrl=${this.backUrl}`
							})
						}
						this.wechatIsRegist = res.data
					}

				});

			},
			// // 密码登录
			// loginByPassword() {
			// 	const that = this
			// 	api.post(
			// 		`/auth/oauth2/token?username=${this.account}&grant_type=password&scope=server&password=${this.password}`, {
			// 			isLogin: true,
			// 		}, ).then(res => {
			// 		if (!res.data) {
			// 			this.isRegist = false;
			// 			this.isRequest = true;
			// 			uni.$u.toast("手机号未注册");
			// 			// userRegist();
			// 		} else {
			// 			this.getCode();
			// 		}

			// 		if (type == "phone") {
			// 			if (!res.data) {
			// 				this.isRegist = false;
			// 				this.isRequest = true;
			// 				uni.$u.toast("手机号未注册");
			// 				// userRegist();
			// 			} else {
			// 				this.userLogin(type);
			// 			}
			// 		}
			// 		if (type == "password") {
			// 			if (!res.data) {
			// 				this.isRegist = false;
			// 				this.isRequest = true;
			// 				uni.$u.toast("该帐号未注册，请切换验证码登陆注册！");
			// 				// userRegist();
			// 			} else {
			// 				this.loginByPassword()
			// 				// this.userLogin(type);
			// 			}
			// 		}
			// 		if (type == "wechat") {
			// 			if (res.data) {
			// 				this.userLogin(type)
			// 			} else {
			// 				console.log("这里5")
			// 				uni.navigateTo({
			// 					url: `/pages/account/pages/info?phone=${this.account}&code=${this.captcha}&backUrl=${this.backUrl}`
			// 				})
			// 			}
			// 			this.wechatIsRegist = res.data
			// 		}

			// 	});
			// },
			// 用户注册
			userRegist() {
				const that = this
				api
					.post(
						"/user/api/auth/phoneRegister", {
							phone: this.account,
							code: this.captcha,
							shareId: this.shareId,
						}, {
							isLogin: true,
							noCheck: true,
						}
					)
					.then((res) => {
						// if (res && res.code == 1) {
						// 	return uni.$u.toast(res.msg);
						// }
						if (res && res.user_id) {
							this.$storage.setItem("token", res.access_token);
							this.$store.commit('setToken', res.access_token)
							this.$storage.setItem("tokenType", res.token_type);
							this.$storage.setItem("refreshToken", res.refresh_token);
							that.getBasicUserInfo()
						}else {
							return uni.$u.toast(res.msg);
						}
						// if (res.data) {
						// 	this.userLogin();
						// }
						console.log("用户注册");
					});
			},
			getBasicUserInfo() {
				api.get("/user/api/auth/userInfo").then((res) => {
					console.log("用户信息1");
					console.log(res);
					if (res && res.code == 0) {
						const data = res.data
						let userType = data.identityType

						if (data.identityType == 1) {
							if (data.dealer) {
								this.$storage.setItem("userType", 3);
								userType = 3
							} else if (!data.manager && !data.guide && !data.dealer) {

								this.$storage.setItem("userType", 4);
								userType = 4
							} else if (data.manager) {
								this.$storage.setItem("userType", 2);
								userType = 2

							} else if (data.guide) {
								this.$storage.setItem("userType", 1);
								userType = 1

							}

						} else if (data.identityType == 2) {
							this.$storage.setItem("userType", 3);
							userType = 3
						} else {
							this.$storage.setItem("userType", data.identityType + 2);
							userType = data.identityType + 2
						}
						console.log('userTypeuserType,', userType)
						this.$store.commit('setUserType', userType)
						if (data) {
							this.$store.commit('setUserInfo', data)
							this.$storage.setItem("basicUnserInfo", data)
							// const platformInfo = uni.getStorageSync("platformInfo")
							const platformInfo = this.$storage.getItem('platformInfo') || {}
							console.log("登录流程")
							console.log(platformInfo)
							console.log(userType)
							console.log(data.dealerAuditStatus)
							if (platformInfo.tenantType == 0) {
								console.log("平台小程序的登录流程")
								console.log(platformInfo)
								console.log(data)
								if (userType == 3 && !data.dealerAuditStatus) {
									console.log("这里1")
									uni.navigateTo({
										url: "/pages/common/pages/introduce"
									})
									this.reloadPage()
								} else {
									console.log("这里2")
									this.bindPage();
								}
							} else {
								console.log("这里8")
								this.bindPage();
							}
							// if (this.appId == "wxdd90ffc3848954d8") {
							// 	if (userType == 3 && !data.dealerAuditStatus) {
							// 		uni.navigateTo({
							// 			url: "/pages/index/introduce"
							// 		})
							// 	} else {
							// 		this.bindPage();
							// 	}

							// 	console.log("平台小程序")
							// 	console.log(data)
							// } else {
							// 	this.bindPage();

							// }
						}
					} else {

					}
				});
			},
			// 登录接口
			userLogin(type) {
				const that = this
				console.log("用户登录");
				// auth/oauth2/token?grant_type=mobile&scope=server&mobile=APP-SMS@13838384384&code=1234' \

				api
					.post(
						`/auth/oauth2/token?grant_type=mobile&scope=server&mobile=APP-SMS@${this.account}&code=${this.captcha}`, {
							// grant_type: "mobile",
							// scope: "server",
							// mobile: this.account,
							// code: this.captcha
						}, {
							isLogin: true,
							noCheck: true
						}
					)
					.then((res) => {
						console.log("登录结果");
						// this.$storage.setItem("token",res)
						console.log(res);
						if (res && res.code) {
							uni.$u.toast(res.msg);
							return;
						}
						if (res && res.user_id) {
							this.$storage.setItem("token", res.access_token);
							this.$store.commit('setToken', res.access_token)
							this.$storage.setItem("tokenType", res.token_type);
							this.$storage.setItem("refreshToken", res.refresh_token);
							if (type == "phone") {

								that.getBasicUserInfo()
							}
						}
						if (type == "wechat") {
							console.log("微信登录")
							uni.login({
								success(res) {
									console.log("获取微信code")
									console.log(res)
									api.post(`/user/api/auth/bindingWechat`, {
										code: res.code,
										type: "APP-MINI"
									}, {
										noCheck: true
									}).then((result) => {
										console.log("绑定信息")
										console.log(result)
										that.getBasicUserInfo()
									})
								}

							})
						}
					});
			},

		},
	};
</script>

<style lang="scss">
	@include color_page;
</style>

<style lang="scss">
	.password_icon {}
</style>